<template>
<!-- 单人-音视频界面 -->
	<view class="wechat-container">
		<!-- 顶部导航栏 -->
		<view class="wechat-header">
			<view class="header-left">
				<i class="" @click="goBack">返回</i>
				<span class="contact-name">{{ contactName }}</span>
			</view>
			<view class="header-right">
				<!-- #ifdef H5 -->
				<img src="@/static/images/microphone.svg" style="width: 18px;filter: brightness(0) invert(1);"
					@click="startVoiceCall('voice')" alt="" />
				<img src="@/static/images/video.svg" style="width: 22px;filter: brightness(0) invert(1);margin-left: 10px;"
					@click="startVideoCall('video')" alt="" />
				<!-- #endif -->
				<!-- #ifdef APP -->
				<i @click="startVoiceCall('voice')"> 语音</i>
				<i @click="startVideoCall('video')"> 视频</i>
				<!-- #endif -->
			</view>
		</view>

		<!-- 聊天内容区域 -->
		<view class="chat-content" ref="chatContent">
			<view v-for="(message, index) in messages" :key="index"
				:class="['message', message.sender === 'me' ? 'message-me' : 'message-other']">
				<view class="message-avatar" v-if="message.sender === 'other'">
					<img :src="contactAvatar" alt="avatar">
				</view>
				<view class="message-content">
					<view class="message-bubble" :class="{'voice-message': message.type === 'voice'}">
						<template v-if="message.type === 'text'">
							{{ message.content }}
						</template>
						<template v-else-if="message.type === 'voice'">
							<i class="fa icon-microphone"></i>
							<span>{{ message.duration }}"</span>
						</template>
						<template v-else-if="message.type === 'image'">
							<img :src="message.content" class="message-image">
						</template>
					</view>
				</view>
				<view class="message-avatar" v-if="message.sender === 'me'">
					<img :src="myAvatar" alt="avatar">
				</view>
			</view>
		</view>
		<!-- 语音、视频组件 -->
<!-- 
		<VoiceContainer v-if="callType == 'voice'" :channel-info="channelInfo" :user-info="userInfo"
			:contact-info="contactInfo" :is-self="isSelf" @call-action="handleCallAction" />
		<VideoContainer v-if="callType == 'video'" :channel-info="channelInfo" :user-info="userInfo"
			:contact-info="contactInfo" :is-self="isSelf" @call-action="handleCallAction" />-->
		<!-- 语音通话弹窗 -->
		<view class="call-modal" v-if="callType == 'voice'" style="background-color: none;">
			<!-- web 浏览器组件，可以用来承载网页的容器 -->
			<web-view v-if="callType == 'voice'" style="display: none;" :src="webSrc" @message="handleMessage"
				:style="{'display':callType === 'voice'?'block':'nonde'}"></web-view>
		</view>
		<!-- 视频通话弹窗 -->
			<view class="call-modal" v-if="callType == 'video'" style="background-color: none;">
			<web-view v-if="callType == 'video'"  ref="myView1" id="myWebview1"  style="display: none;" :src="webSrc" 
				@message="handleMessage1" :style="{'display':callType === 'video'?'block':'nonde'}"></web-view>
		</view>

	</view>
</template>

<script>
	// import VoiceContainer from './components/VoiceContainer.vue'
	// import VideoContainer from './components/VideoContainer.vue'
	import {
		storage
	} from '@/utils/storage.js';
	export default {
		name: 'WeChatChat',
		// components: {
		// 	VoiceContainer,
		// 	VideoContainer
		// },
		data() {
			return {
				contactName: '',
				contactAvatar: 'https://obs-ykl.obs.cn-south-1.myhuaweicloud.com/uploads/images/e0/6c8410e4c38c4fcc7b4ca426c2bbb0.jpg',
				myAvatar: 'https://hkimg.buildmost.com/image/20240913/30acfc72-d231-4fc2-8255-f3063db2aa48.jpeg',
				messages: [{
						sender: 'other',
						type: 'text',
						content: '你好啊！最近怎么样？'
					},
					{
						sender: 'me',
						type: 'text',
						content: '还不错，你呢？'
					},
					{
						sender: 'other',
						type: 'voice',
						duration: 5
					},
					{
						sender: 'me',
						type: 'voice',
						duration: 3
					},
					{
						sender: 'other',
						type: 'image',
						content: 'https://www.baidu.com/img/flexible/logo/pc/result.png'
					}
				],
				inputText: '',
				isVoiceInput: false,
				callType: '', // '', 'voice', 'video'
				isRecording: false,
				recordTimer: null,
				recordDuration: 0,
				userInfo: {},
				contactInfo: {},
				webSrc: '',
				isSelf: false, // 是否是自己
				callStatus: 'idle',
				VoiceShow: false,
				channelInfo:{
				// 频道
				// appId: '584d8608c53e4d3cbb3c630feef2b888',
				// channel: 'test_channel',
				// token: '007eJxTYOgI1GrIcvKbmSd+WNXnS/6p5QdF3gUcOl+QvVHvwor9pz0UGEwtTFIszAwskk2NU01SjJOTkoyTzYwN0lJT04ySLCwsJM7LZjQEMjKs+/WPgREKQXwehpLU4pL45IzEvLzUHAYGAJnhJEg=',
				// token 24小时更换，appid本月结束
				appId:'a04122acf42f4b0c92e104ff4c863fde',
				channel:'shiproom',
				token:'007eJxTYFidk/1qqYAcg+y6A/q+ZexSVmueLth7+uxLhwcPBRaXT3yowJBoYGJoZJSYnGZilGaSZJBsaZRqaGCSlmaSbGFmnJaSeuyDckZDICPD/qIwRkYGCATxORiKMzILivLzcxkYAPz9Il8=',
				},
			}
		},
		onLoad(options) {
			this.userInfo = storage.getItem('userInfo') ? (storage.getItem('userInfo')) : {}
			this.userId = options.userId
			this.contactName = options.userName
			this.type = options.type
			// 
			this.contactInfo = {
				userId: this.userId,
				contactName: this.contactName,
				contactAvatar: this.contactAvatar,
				status: 'waiting'
			}
			/**
			 * 用户信息  接听界面-传参
			 *  appid: '', // appId
			 *  token: '', // 根据房间号生成的token(房间号和token对应)
			 * channel: '', // 房间号(房间号和token对应)
			***/
			// API获取系统信息
			console.log('userId', this.userInfo.id, this.userId)
			uni.getSystemInfo({
				success: function(res) {
					console.log('系统信息', res)
				}
			})
		},
		mounted() {
			// #ifdef H5
			this.scrollToBottom()
			window.addEventListener("message", this.handleH5Message);
			// #endif
			// this.getChannel()
		},
		methods: {
			goBack() {
				// #ifdef H5
				window.history.go(-1); // 使用浏览器原生返回
				// #endif

				// #ifdef APP-PLUS
				uni.navigateBack(1); // 原生应用使用标准返回
				// #endif
			},
			getChannel(type){
				console.log('type', type)
				// this.channelInfo.channel = this.userInfo.id+'_'+ new Date().getTime() //有推送的情况时间戳更新
				this.channelInfo.channel = this.type==2?this.userId+'_'+this.userInfo.id : this.userInfo.id+'_'+this.userId
				const data={
					channelName:this.channelInfo.channel,
					userId:this.userInfo.id
				}
					uni.request({
					  url: 'http://192.168.119.174:8091/build-app/audioAndVideo/getUserToken', // 接口地址
					  method: 'Post', // 请求方法 GET/POST/PUT/DELETE等
					  data: data,
					  header: { // 请求头
					    'Content-Type': 'application/json',
					  },
					  success: (res) => {
					    console.log('请求成功:', res.data);
							if(res.data.data){
								this.channelInfo.appId = res.data.data.appId
								this.channelInfo.token = res.data.data.token
								console.log('channelInfo',this.channelInfo)
								this.showPage(type)
							}
					    // 处理返回数据
					  },
					  fail: (err) => {
					    console.error('请求失败:', err);
					    // 处理错误
					  },
					  complete: () => {
					    // 请求完成回调
					  }
					});
			},
			handleCallAction(action) {
				// 处理通话动作（接听、拒接、挂断等）
				console.log('通话动作:', action);
				const data = action
				if (data && data.callerId) {
					if (data.callerId == 'caller' && !data.status) {
						this.callType = '';
						const msg = data.userId == this.userInfo.id ? '已取消' : '对方拒接'
						console.log('msg', msg)
						setTimeout(() => {
							uni.showToast({
								title: msg,
								icon: 'none'
							})
						}, 1000)
					} else if (data.callerId == 'handelUp') {
						this.callType = '';
						setTimeout(() => {
							const msg = data.userId == this.userInfo.id ? '已挂断' : '对方已挂断'
							console.log('msg', msg)
							uni.showToast({
								title: msg,
								icon: 'none'
							})
						}, 1000)
					} else if (data.callerId == 'audioCall') {
						this.callType = '';
						setTimeout(() => {
							uni.showToast({
								title: data.error,
								icon: 'none'
							})
						}, 1000)
					}
				}
			},
			// 处理标准 message 事件
			handleH5Message(e) {
				const that = this
				console.log('handleH5Message收到消息:', e.data,e.data==undefined||e.data.data==undefined);
				if(e.data==undefined||e.data.data==undefined){
					return
				}
				const data = e.data.data.arg ? e.data.data.arg : e.data.data || {}
				console.log('data', data)
				if (data && data.callerId) {
					if (data.callerId == 'caller' && !data.status) {
						this.callType = '';
						const msg = data.userId == this.userInfo.id ? '已取消' : '对方拒接'
						console.log('msg', msg)
						setTimeout(() => {
							uni.showToast({
								title: msg,
								icon: 'none'
							})
						}, 1000)
					} else if (data.callerId == 'handelUp') {
						this.callType = '';
						setTimeout(() => {
							const msg = data.userId == this.userInfo.id ? '已挂断' : '对方已挂断'
							console.log('msg', msg)
							uni.showToast({
								title: msg,
								icon: 'none'
							})
						}, 1000)
					} else if (data.callerId == 'audioCall') {
						this.callType = '';
						setTimeout(() => {
							uni.showToast({
								title: data.error,
								icon: 'none'
							})
						}, 1000)
					}
				}
			},
			// 语音通话回传
			handleMessage(e) {
				console.log('handleMessage收到消息:', e);
				const data = e.detail.data[0]
				console.log('data', data)
				if (data && data.callerId) {
					if (data.callerId == 'caller' && !data.status) {
						this.callType = '';
						const msg = data.userId == this.userInfo.id ? '已取消' : '对方拒接'
						console.log('msg', msg)
						setTimeout(() => {
							uni.showToast({
								title: msg,
								icon: 'none'
							})
						}, 1000)
					} else if (data.callerId == 'handelUp') {
						this.callType = '';
						setTimeout(() => {
							const msg = data.userId == this.userInfo.id ? '已挂断' : '对方已挂断'
							console.log('msg', msg)
							uni.showToast({
								title: msg,
								icon: 'none'
							})
						}, 1000)
					} else if (data.callerId == 'audioCall') {
						this.callType = '';
						setTimeout(() => {
							uni.showToast({
								title: data.error,
								icon: 'none'
							})
						}, 1000)
					}
				}
			},
			// 拨打语音按钮
			async startVoiceCall(type) {
				await this.getChannel(type)
			},
			showPage(type) {
				console.log({type});
				this.callType = type;//展示通话弹窗
				this.isSelf = true
				console.log('传值',this.channelInfo);
				this.$nextTick(() => {
					this.callStatus = 'idle'
					const userInfo = JSON.stringify(this.userInfo)
					const contactInfo = JSON.stringify(this.contactInfo)
					const pageHtml = type=='voice'?'chartVoice':'chartVideo'
					this.webSrc = '../../static/'+pageHtml+'.html?channelInfo=' + encodeURIComponent(JSON.stringify(this.channelInfo)) +
						'&userInfo=' + encodeURIComponent(userInfo) + '&contactInfo=' + encodeURIComponent(contactInfo) +
						'&isSelf=true'
				})
			},
			// 结束视频
			endVoiceCall(e) {
				console.log('e', e)
				this.callType = ''
			},
			async startVideoCall(type){// 拨打视频通话按钮
				await this.getChannel(type)
			},
			// 结束视频
			endVideoCall(e) {
				console.log('e', e)
				this.callType = ''
			},
			toggleInputType() {
				this.isVoiceInput = !this.isVoiceInput;
			},
			sendTextMessage() {
				if (this.inputText.trim()) {
					this.messages.push({
						sender: 'me',
						type: 'text',
						content: this.inputText
					});
					this.inputText = '';
					this.scrollToBottom();

					// 模拟回复
					setTimeout(() => {
						this.messages.push({
							sender: 'other',
							type: 'text',
							content: '这是自动回复消息'
						});
						this.scrollToBottom();
					}, 1000);
				}
			},
			startRecord() {
				this.isRecording = true;
				this.recordDuration = 0;
				this.recordTimer = setInterval(() => {
					this.recordDuration++;
				}, 1000);
				console.log('开始录音');
			},
			stopRecord() {
				if (this.isRecording) {
					clearInterval(this.recordTimer);
					this.isRecording = false;
					console.log('结束录音，时长:', this.recordDuration + '秒');

					// 发送语音消息
					this.messages.push({
						sender: 'me',
						type: 'voice',
						duration: this.recordDuration
					});
					this.scrollToBottom();

					// 模拟回复
					setTimeout(() => {
						this.messages.push({
							sender: 'other',
							type: 'voice',
							duration: Math.floor(Math.random() * 5) + 1
						});
						this.scrollToBottom();
					}, 1500);
				}
			},
			cancelRecord() {
				if (this.isRecording) {
					clearInterval(this.recordTimer);
					this.isRecording = false;
					console.log('取消录音');
				}
			},
			scrollToBottom() {
				this.$nextTick(() => {
					const container = this.$refs.chatContent;
					container.scrollTop = container.scrollHeight;
				});
			}
		},
	}
</script>

<style scoped>
	/* 基础样式 */
	* {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}

	/deep/ .uni-web-view.uni-webview--fullscreen {
		/* top: 44px !important; */
		display: none !important;
		height: 0 !important;
	}

	/deep/ iframe {
		/* z-index: -1; */
		z-index: 9;
		/* top: 44px !important; */
		/* display: none !important; */
	}

	.wechat-container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #ededed;
		font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
	}

	/* 头部样式 */
	.wechat-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10px 15px;
		background-color: #2e2e2e;
		color: white;
		height: 50px;
		/* z-index: 99; */
	}

	.header-left,
	.header-right {
		display: flex;
		align-items: center;
	}

	.fa {
		font-size: 22px;
		margin: 0 10px;
		cursor: pointer;
	}

	.contact-name {
		font-size: 18px;
		margin-left: 10px;
	}

	/* 聊天内容区域 */
	.chat-content {
		flex: 1;
		overflow-y: auto;
		padding: 10px;
		background-color: #f5f5f5;
	}

	.message {
		display: flex;
		margin-bottom: 15px;
	}

	.message-avatar {
		width: 40px;
		height: 40px;
		border-radius: 4px;
		overflow: hidden;
		margin: 0 10px;
	}

	.message-avatar img {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.message-content {
		max-width: 70%;
		display: flex;
		align-items: center;
	}

	.message-me .message-content {
		flex-direction: row-reverse;
	}

	.message-bubble {
		padding: 10px 15px;
		border-radius: 4px;
		position: relative;
		word-break: break-word;
		line-height: 1.4;
	}

	.message-other .message-bubble {
		background-color: white;
		color: #333;
	}

	.message-me .message-bubble {
		background-color: #95ec69;
		color: #333;
	}

	.voice-message {
		display: flex;
		align-items: center;
	}

	.message-image {
		max-width: 200px;
		max-height: 200px;
		border-radius: 4px;
	}

	/* 输入区域 */
	.input-area {
		display: flex;
		align-items: center;
		padding: 8px 10px;
		background-color: #f5f5f5;
		border-top: 1px solid #ddd;
	}

	.input-tools {
		display: flex;
		margin-right: 10px;
	}

	.input-main {
		flex: 1;
	}

	.input-main input {
		width: 100%;
		padding: 8px 12px;
		border: none;
		border-radius: 4px;
		outline: none;
		font-size: 16px;
	}

	.voice-input {
		width: 100%;
		padding: 8px 0;
		text-align: center;
		background-color: white;
		border-radius: 4px;
		cursor: pointer;
	}

	.input-send {
		margin-left: 10px;
	}

	.input-send button {
		padding: 8px 15px;
		background-color: #07c160;
		color: white;
		border: none;
		border-radius: 4px;
		cursor: pointer;
	}

	/* 通话弹窗 */
	.call-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		/* background-color: rgba(0, 0, 0, 0.8); */
		display: flex;
		justify-content: center;
		align-items: center;
		/* z-index: 1000; */
	}

	.call-content {
		background-color: #666;
		color: white;
		padding: 30px;
		border-radius: 10px;
		text-align: center;
		width: 300px;
	}

	.video-call {
		width: 100%;
		height: 100%;
		padding: 0;
		border-radius: 0;
	}

	.call-avatar {
		width: 100px;
		height: 100px;
		border-radius: 50%;
		overflow: hidden;
		margin: 0 auto 20px;
	}

	.call-avatar img {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.call-info h3 {
		margin-bottom: 10px;
		font-size: 20px;
	}

	.call-actions {
		margin-top: 30px;
		display: flex;
	}

	.call-end {
		margin: auto;
		width: 60px;
		height: 60px;
		border-radius: 50%;
		background-color: #f44336;
		color: white;
		border: none;
		font-size: 24px;
		cursor: pointer;
	}

	.call-agree {
		background: green;
	}

	/* 视频通话样式 */
	.video-container {
		width: 100%;
		height: 100%;
		position: relative;
	}

	.remote-video {
		width: 100%;
		height: 100%;
	}

	.remote-video video {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.local-video {
		position: absolute;
		bottom: 20px;
		right: 20px;
		width: 120px;
		height: 160px;
		border-radius: 6px;
		overflow: hidden;
		background-color: #333;
	}

	.local-video video {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.video-actions {
		display: flex;
		justify-content: center;
		margin-top: 10px;
	}

	.video-actions button {
		width: 40px;
		height: 40px;
		border-radius: 50%;
		background-color: rgba(255, 255, 255, 0.2);
		color: white;
		border: none;
		margin: 0 5px;
		cursor: pointer;
	}

	.video-actions .call-end {
		background-color: #f44336;
	}
</style>